<?php
/**
 * API处理器基类
 * 提供API的基础功能，如请求处理、响应格式化等
 */

class ApiHandler {
    protected $db;
    protected $user;
    protected $requestMethod;
    protected $requestData;
    protected $endpoint;
    protected $params = [];
    
    /**
     * 构造函数
     * @param string $endpoint API端点
     */
    public function __construct($endpoint = '') {
        // 设置响应头
        header('Content-Type: application/json');
        header('Access-Control-Allow-Origin: *');
        header('Access-Control-Allow-Methods: GET, POST, PUT, DELETE');
        header('Access-Control-Allow-Headers: Content-Type, Authorization');
        
        // 加载依赖
        require_once __DIR__ . '/../include/Database.php';
        require_once __DIR__ . '/../include/User.php';
        
        $this->db = Database::getInstance();
        $this->user = new User();
        $this->endpoint = $endpoint;
        $this->requestMethod = $_SERVER['REQUEST_METHOD'];
        
        // 获取请求数据
        $this->parseRequestData();
    }
    
    /**
     * 解析请求数据
     */
    protected function parseRequestData() {
        // 处理URL参数
        if (isset($_GET) && !empty($_GET)) {
            $this->params = $_GET;
        }
        
        // 处理请求体
        switch ($this->requestMethod) {
            case 'GET':
                $this->requestData = $_GET;
                break;
            case 'POST':
                $input = file_get_contents('php://input');
                if (strlen($input) > 0) {
                    $this->requestData = json_decode($input, true);
                } else {
                    $this->requestData = $_POST;
                }
                break;
            case 'PUT':
            case 'DELETE':
                $input = file_get_contents('php://input');
                $this->requestData = json_decode($input, true);
                break;
            default:
                $this->requestData = [];
                break;
        }
        
        // 如果JSON解析失败，使用空数组
        if ($this->requestData === null) {
            $this->requestData = [];
        }
    }
    
    /**
     * 处理请求
     */
    public function processRequest() {
        // 请求方法不支持时，返回错误
        if (!method_exists($this, $this->requestMethod)) {
            $this->sendResponse(['error' => 'Method not allowed'], 405);
            return;
        }
        
        // 调用对应的请求方法
        $this->{$this->requestMethod}();
    }
    
    /**
     * 验证API访问权限
     * @param bool $requireAuth 是否需要登录
     * @param string $requiredRole 需要的角色（可选）
     * @return bool 是否有权限
     */
    protected function validateAccess($requireAuth = true, $requiredRole = '') {
        // 检查是否需要身份验证
        if ($requireAuth && !$this->user->isLoggedIn()) {
            $this->sendResponse(['error' => 'Unauthorized access'], 401);
            return false;
        }
        
        // 如果指定了角色要求，检查用户是否具有该角色
        if ($requiredRole && !$this->user->hasRole($requiredRole)) {
            $this->sendResponse(['error' => 'Permission denied'], 403);
            return false;
        }
        
        return true;
    }
    
    /**
     * 发送API响应
     * @param mixed $data 响应数据
     * @param int $statusCode HTTP状态码
     */
    protected function sendResponse($data, $statusCode = 200) {
        http_response_code($statusCode);
        echo json_encode($data);
        exit;
    }
    
    /**
     * 获取请求参数
     * @param string $key 参数名
     * @param mixed $default 默认值
     * @return mixed 参数值
     */
    protected function getParam($key, $default = null) {
        if (isset($this->requestData[$key])) {
            return $this->requestData[$key];
        }
        
        if (isset($this->params[$key])) {
            return $this->params[$key];
        }
        
        return $default;
    }
    
    /**
     * 验证必填参数
     * @param array $required 必填参数数组
     * @return bool 验证结果
     */
    protected function validateRequiredParams($required) {
        $missing = [];
        
        foreach ($required as $param) {
            if (!isset($this->requestData[$param]) && !isset($this->params[$param])) {
                $missing[] = $param;
            }
        }
        
        if (!empty($missing)) {
            $this->sendResponse([
                'error' => 'Missing required parameters',
                'missing' => $missing
            ], 400);
            return false;
        }
        
        return true;
    }
    
    // 默认的HTTP方法处理函数，子类应重写这些方法
    
    /**
     * 处理GET请求
     */
    protected function GET() {
        $this->sendResponse(['error' => 'GET method not implemented'], 501);
    }
    
    /**
     * 处理POST请求
     */
    protected function POST() {
        $this->sendResponse(['error' => 'POST method not implemented'], 501);
    }
    
    /**
     * 处理PUT请求
     */
    protected function PUT() {
        $this->sendResponse(['error' => 'PUT method not implemented'], 501);
    }
    
    /**
     * 处理DELETE请求
     */
    protected function DELETE() {
        $this->sendResponse(['error' => 'DELETE method not implemented'], 501);
    }
} 